package com.ntt.benew.dictionary.api

/**
 * Created by Android Studio.
 * User: tw
 * Date: 2023/11/2
 * Time: 17:58
 */

import com.ntt.benew.dictionary.utils.HttpUtil
import com.ntt.benew.dictionary.utils.binary.DigestUtils
import com.ntt.core.nlogger.NLogger
import java.net.URLDecoder
import java.util.*


/**
 * 有道查词接入有道少儿API
 * 接口返回请查看文档
 * https://ai.youdao.com/DOCSIRMA/html/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E7%BF%BB%E8%AF%91/API%E6%96%87%E6%A1%A3/%E5%B0%91%E5%84%BF%E8%AF%8D%E5%85%B8%E6%9C%8D%E5%8A%A1/%E5%B0%91%E5%84%BF%E8%AF%8D%E5%85%B8%E6%9C%8D%E5%8A%A1-API%E6%96%87%E6%A1%A3.html
 */
object YDDictManager {

    //语言自动
    const val LANG_AUTO = "auto"

    //英文
    const val LANG_EN = "en"

    //中文
    const val LANG_ZH_CHS = "zh-CHS"

    //有道AppID
    private const val YD_APP_ID = "0ddac560ebfab015"

    //有道AppKey
    private const val YD_APP_KEY = "OBRHlfVQ3MCbiiTimcorD7AU4BVsyQ9y"

    //有道查词API
    private const val YD_HOST_URL = "https://openapi.youdao.com/"

    //有道翻译
    private const val YD_TRANSLATE = "api"

    // 有道少儿词典
    private const val YD_KID_DICT = "v2/kid_dict"

    /**
     * 有道签名
     */
    private fun generateYDSign(word: String, uuid: String, curTime: String): String {
        val input = generateYDSignInput(word)
        return DigestUtils.sha256Hex(YD_APP_ID + input + uuid + curTime + YD_APP_KEY)
    }

    /**
     *  有道签名Input
     */
    private fun generateYDSignInput(word: String): String {
        return if (word.length <= 20) {
            word
        } else {
            val length = word.length
            word.substring(0, 10) + length + word.substring(length - 10, length)
        }
    }


    /**
     *  有道词典查词
     *  @param word 查询内容，支持中英文
     *  @param langType 语言类型
     *  @return 返回Observable对象客户端实现数据流处理
     */
    fun queryDictWord(word: String, langType: String): String? {
        val uuid = UUID.randomUUID().toString()
        val curTime = (System.currentTimeMillis() / 1000).toString()
        val params = HashMap<String, String>()
        params["q"] = decodeWord(word)
        params["langType"] = langType
        params["appKey"] = YD_APP_ID
        params["salt"] = uuid
        params["sign"] = generateYDSign(word, uuid, curTime)
        params["signType"] = "v3"
        params["docType"] = "json"
        params["curtime"] = curTime
        val url = YD_HOST_URL + YD_KID_DICT
        NLogger.d("有道查词接口参数：${params.toString()}")
        val body = StringBuffer()
        params.keys.forEach {
            body.append("$it=${params[it]}&")
        }
//        val headerMap = mutableMapOf<String,String>(
//
//        )
//        val body = "q=tracking&curtime=$curTime&salt=ea55f6fa-1149-470b-93a6-619b4a6f478a&sign=${generateYDSign(word, uuid, curTime)}&signType=v3&appKey=0ddac560ebfab015&langType=en"
        return HttpUtil.doPost1(url, null, body.toString())

    }



    /**
     * 有道文本翻译
     *  @param word 翻译内容
     *  @param fromLang 源语言
     *  @param toLang 目标语言
     */
//    fun translateWord(
//        word: String,
//        fromLang: String,
//        toLang: String
//    ): Observable<Map<String, Any>> {
//        val uuid = UUID.randomUUID().toString()
//        val curTime = (System.currentTimeMillis() / 1000).toString()
//        val params = HashMap<String, String>()
//        params["q"] = decodeWord(word)
//        params["from"] = fromLang
//        params["to"] = toLang
//        params["appKey"] = YD_APP_ID
//        params["salt"] = uuid
//        params["sign"] = generateYDSign(word, uuid, curTime)
//        params["signType"] = "v3"
//        params["curtime"] = curTime
//        return obtainService(retrofitYD, YDDictService::class.java)
//            .postYDTranslate(params)
//    }

    /**
     * 对查询内容编码
     */
    private fun decodeWord(word: String): String {
        val translateWord = word.replace("%(?![0-9a-fA-F]{2})".toRegex(), "%25")
        return URLDecoder.decode(translateWord, "UTF-8")
    }
}